<?php

namespace App\Admin\Controllers\Videos;

use App\Models\VideoCategory;
use App\Models\Video;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use App\Models\SystemConfig;
use App\Models\AgentPrice;
use App\Models\CdnDomain;
use App\Services\ConfigService;

use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Layout\Column;
use Illuminate\Http\Request;

use Dcat\Admin\Widgets\Alert;
use App\Admin\Actions\Grid\ImportVideoAction;
use App\Admin\Actions\Grid\VideoBatchSetting;

class VideoController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        //图片服务器域名
        $img_domain = cache()->rememberForever('img_domain',  function () {
            //落地有可能没有了，所以加锁防止没有时缓存穿透
            return cache()->lock('img_domain')->get(function () {
                // 获取无限期锁并自动释放...
                return CdnDomain::show()->where('type',1)->value('domain');
            });
        });
        return Grid::make(new Video(), function (Grid $grid)use($img_domain) {
            $grid->model()->with('category');
            $grid->column('id')->sortable();
            $grid->column('title')->width(300)->editable();
            $grid->column('face_img')
            ->display(function($v)use($img_domain){
                return "http://{$img_domain}{$v}.jpg";
            })->image(80,80);
            
            $grid->column('category_id','分类')->sortable()->select(VideoCategory::show()->pluck('name','id'),true);
            $grid->column('state')->switch('', true)->sortable();
            $grid->column('is_recommend')->switch('', true)->sortable();
            $grid->column('time')->sortable();
            $grid->column('paynum')->sortable();
            $grid->column('updated_at')->sortable();
        
            // $grid->disableFilterButton();
            // $grid->quickSearch(['id', 'title', 'url']);
            
            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->equal('id')->width(2);
                $filter->like('url')->width(5);
                $filter->where('title', function ($query) {
                    //缓存视频库
                    $titles = cache()->remember('admin_videos_titles', 86400,function (){
                        $videos = Video::select(['id','title'])->get();
                        if(count($videos)){
                            return $videos->toArray();
                        }
                        return [];
                    });
                    $ids = [];
                    //获取匹配的id
                    if(count($titles)){
                        foreach($titles as $item){
                            if (strstr( $item['title'] , $this->input ) !== false ){
                                $ids[] = $item['id'];
                            }
                        }
                    }
                    $query->whereIn('id',$ids);
                
                })->width(4);
        
            });
            $grid->tools([new ImportVideoAction()]); 
            $grid->tools([new VideoBatchSetting()]);   
            
            $grid->selector(function (Grid\Tools\Selector $selector) {
                $selector->select('category_id', '分类',VideoCategory::show()->pluck('name','id') );
                $selector->selectOne('is_recommend', '是否推荐', [
                    1 => '推荐的',
                    0 => '否',
                ]);
                $selector->selectOne('state', '是否显示', [
                    1 => '显示中',
                    0 => '未显示',
                ]);
            });
            $grid->enableDialogCreate();
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Video(), function (Show $show) {
            $show->field('id');
            $show->field('title');
            $show->field('face_img');
            $show->field('url');
            $show->field('category_id');
            $show->field('state');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Video(), function (Form $form) {
            $form->display('id');
            $form->text('title')->required();
            $form->text('face_img');
            $form->text('url')->required();
            $form->select('category_id')->options(VideoCategory::show()->pluck('name','id'))->required();
            // $form->radio('state')->options([1 => '启用',-1=>'停用'])->default(1);
        
            $form->switch('state')->default(1);
            $form->switch('is_recommend')->default(1);
            $form->display('created_at');
            $form->display('updated_at');

            $form->saved(function(Form $form){
                cache()->forget('init_videos');
            });

            $form->deleted(function (Form $form, $result) {
                // 获取待删除行数据，这里获取的是一个二维数组
                $data = $form->model()->toArray();
                // 通过 $result 可以判断数据是否删除成功
                if (! $result) {
                    return $form->response()->error('数据删除失败');
                }
                cache()->forget('init_videos');
                // 返回删除成功提醒，此处跳转参数无效
                return $form->response()->success('删除成功');
            });
        });
    }






    /*
     *  视频金额设置
     */

    public function videoConfForm(Content $content)
    {
        
        $conf = ConfigService::videoPriceConfig();
        $form = Form::make($conf, function (Form $form)use($conf) {

            $form->embeds('content', '', function ($form) use ($conf) {
                $form->decimal('min_price', '最低金额')->type('number')->attribute('min', 1)->default($conf['content']['min_price'])->help('视频打赏最低金额');
                $form->decimal('max_price', '最高金额')->type('number')->attribute('min', 1)->default($conf['content']['max_price'])->help('视频打赏最高金额');
            });
            
            $form->disableHeader();
            $form->footer(function ($footer) {

                // 去掉`重置`按钮
                $footer->disableReset();

                // 去掉`查看`checkbox
                $footer->disableViewCheck();
            
                // 去掉`继续编辑`checkbox
                $footer->disableEditingCheck();
            
                // 去掉`继续创建`checkbox
                $footer->disableCreatingCheck();
            });
        });

        $callout = Alert::make( '固定金额请把最低和最高金额填写成一样的','提示');

        // 颜色
        
        return $content->body(function (Row $row) use($form,$callout){
            $row->column(6, function (Column $column) use($form,$callout) {
                $column->row($callout->warning());
                $column->row($form);
            });
        });
        
    }

    //保存视频设置
    public function saveVideoConf(Request $request)
    {
        $conf = ConfigService::videoPriceConfig();
        $arr = $request->input('content');
        //判断最低最高价
        if($arr['min_price']>$arr['max_price']){
            return [
                'status'=>false, 
                'data'=>[
                    'message'=> "最低价不能高于最高价!",
                     'type'=> "error"
                ]
            ];
        }
        //更新系统设置
        $res = $conf->update(['content' => $arr]);
        //判断代理的价格
        AgentPrice::where('min_price','<',$arr['min_price'])->whereOr('min_price','>',$arr['max_price'])->update(['min_price'=>$arr['min_price']]);
        AgentPrice::where('max_price','>',$arr['max_price'])->whereOr('max_price','<',$arr['min_price'])->update(['max_price'=>$arr['max_price']]);
        if($res){
            cache()->forget('system_video_price');
            return [
                'status'=>true, 
                'data'=>[
                    'message'=> "更新成功!",
                     'type'=> "success"
                ]
            ];
        }else{
            return [
                'status'=>false, 
                'data'=>[
                    'message'=> "更新失败!",
                     'type'=> "error"
                ]
            ];
        }
    }
}
